package cn.eslm.flash.api.controller;

import cn.eslm.flash.api.controller.Utils.Excel1;
import cn.eslm.flash.api.controller.Utils.Excel2;
import cn.eslm.flash.api.controller.Utils.Excel3;
import cn.eslm.flash.api.controller.Utils.ExportExcelUtils;
import cn.eslm.flash.bean.entity.cms.Dish;
import cn.eslm.flash.bean.entity.cms.Order;
import cn.eslm.flash.bean.entity.system.FileInfo;
import cn.eslm.flash.bean.entity.system.User;
import cn.eslm.flash.bean.enumeration.Permission;
import cn.eslm.flash.bean.vo.front.Rets;
import cn.eslm.flash.service.cms.DishService;
import cn.eslm.flash.service.cms.OrderService;
import cn.eslm.flash.service.system.FileService;
import cn.eslm.flash.service.system.UserService;
import cn.eslm.flash.utils.CryptUtil;
import cn.eslm.flash.utils.HttpUtil;
import cn.eslm.flash.utils.Maps;
import cn.eslm.flash.utils.StringUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController extends BaseController {
    @Autowired
    private static  final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FileService fileService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private DishService dishService;

    @RequestMapping(method = RequestMethod.POST)
    @RequiresPermissions(value = {Permission.FILE_UPLOAD})
    public Object upload(@RequestPart("file") MultipartFile multipartFile) {

        try {
            FileInfo fileInfo = fileService.upload(multipartFile);
            return Rets.success(fileInfo);
        } catch (Exception e) {
            logger.error("上传文件异常",e);
            return Rets.failure("上传文件失败");
        }
    }


    @RequestMapping(value="download",method = RequestMethod.GET)
    public void download(@RequestParam("idFile") Long idFile,
                           @RequestParam(value = "fileName",required = false) String fileName){
        FileInfo fileInfo = fileService.get(idFile);
        fileName = StringUtil.isEmpty(fileName)? fileInfo.getOriginalFileName():fileName;
        HttpServletResponse response = HttpUtil.getResponse();
        response.setContentType("application/x-download");
        try {
            fileName = new String(fileName.getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;

        OutputStream os = null;
        try {
            File file = new File(fileInfo.getAblatePath());
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }

        } catch (Exception e) {
            logger.error("download error",e);
        }finally {
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                logger.error("close inputstream error", e);
            }
        }

    }
    @RequestMapping(value = "/excelDownload3", method = RequestMethod.GET)
//    @RequiresPermissions(value = {Permission.FILE})
    public void ExportBankCkeckInfo3(HttpServletResponse response, HttpServletRequest request) {
        //这里是笔者实际业务需求中需要得到时间间隔。可忽略
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        System.out.println("打印的起始日期为：" + start + "，打印的结束日期为：" + end);
        //得到所有要导出的数据
        List<Dish> orderlist1 = dishService.queryAll();
        Dish dish = new Dish();
        List<Excel3> list1 = new ArrayList<Excel3>();
        for (int index = 0; index < orderlist1.size(); index++) {
            dish = orderlist1.get(index);
            Excel3 excel = new Excel3();
            excel.setId(dish.getId());
            excel.setTitle(dish.getTitle());
            excel.setContent(dish.getContent());
            excel.setCreated_time(dish.getCreateTime());
            excel.setInventory(dish.getInventory());
            excel.setPrice(dish.getPrice());
            list1.add(excel);
        }
        //定义导出的excel名字
        String excelName = "菜品详情表";
        //获取需要转出的excel表头的map字段
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("id", "菜品编号");
        fieldMap.put("created_time","创建日期");
        fieldMap.put("content", "内容");
        fieldMap.put("price", "价格");
        fieldMap.put("title", "菜品名字");
        fieldMap.put("inventory", "库存");
        //导出用户相关信息
        new ExportExcelUtils().export(excelName, list1, fieldMap, response);
    }
    @RequestMapping(value = "/excelDownload2", method = RequestMethod.GET)
//    @RequiresPermissions(value = {Permission.FILE})
    public void ExportBankCkeckInfo2(HttpServletResponse response, HttpServletRequest request) {
        //这里是笔者实际业务需求中需要得到时间间隔。可忽略
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        System.out.println("打印的起始日期为：" + start + "，打印的结束日期为：" + end);
        //得到所有要导出的数据
        List<User> orderlist1 = userService.queryAll();
        User user = new User();
        List<Excel2> list1 = new ArrayList<Excel2>();
        for (int index = 0; index < orderlist1.size(); index++) {
            user = orderlist1.get(index);
            Excel2 excel = new Excel2();
            excel.setAccount(user.getAccount());
            excel.setCreated_time(user.getCreateTime());
            excel.setPhone(user.getPhone());
            excel.setBirthday(user.getBirthday());
            excel.setEmail(user.getEmail());
            excel.setName(user.getName());
            excel.setSex(user.getSex());
            list1.add(excel);
        }
        //定义导出的excel名字
        String excelName = "用户详情表";
        //获取需要转出的excel表头的map字段
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("account", "账号");
        fieldMap.put("created_time", "创建日期");
        fieldMap.put("phone", "电话");
        fieldMap.put("name", "名字");
        fieldMap.put("sex", "性别");
        fieldMap.put("birthday", "生日");
        fieldMap.put("email", "邮件");
        //导出用户相关信息
        new ExportExcelUtils().export(excelName, list1, fieldMap, response);
    }
    @RequestMapping(value = "/excelDownload1", method = RequestMethod.GET)
//    @RequiresPermissions(value = {Permission.FILE})
    public void ExportBankCkeckInfo(HttpServletResponse response, HttpServletRequest request) {
        //这里是笔者实际业务需求中需要得到时间间隔。可忽略
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        System.out.println("打印的起始日期为：" + start + "，打印的结束日期为：" + end);
        //得到所有要导出的数据
        List<Order> orderlist1 = orderService.queryAll();
        Order order = new Order();
        List<Excel1> list1 = new ArrayList<Excel1>();
        for (int index = 0; index < orderlist1.size(); index++) {
            order = orderlist1.get(index);
            Excel1 excel = new Excel1();
            excel.setId(order.getUserID());
            excel.setCreated_time(order.getCreateTime());
            excel.setMobile(order.getMobile());
            excel.setRemark(order.getRemark());
            excel.setStatus(order.getStatus());
            excel.setUserid(order.getUserID());
            list1.add(excel);
        }
        //定义导出的excel名字
        String excelName = "订单详情表";
        //获取需要转出的excel表头的map字段
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("id", "订单编号");
        fieldMap.put("created_time", "日期");
        fieldMap.put("mobile", "收货电话");
        fieldMap.put("remark", "地址");
        fieldMap.put("status", "订单状态");
        fieldMap.put("userid", "用户编号");
        //导出用户相关信息
        new ExportExcelUtils().export(excelName, list1, fieldMap, response);
    }

    @RequestMapping(value="getImgBase64",method = RequestMethod.GET)
    public Object getImgBase64(@RequestParam("idFile")Long idFile){

        FileInfo fileInfo = fileService.get(idFile);
        FileInputStream fis = null;
        try {
            File file = new File(fileInfo.getAblatePath());
            byte[] bytes = new byte[(int) file.length()];
            fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            bis.read(bytes);
            String base64 = CryptUtil.encodeBASE64(bytes);
            return Rets.success(Maps.newHashMap("imgContent", base64));
        } catch (Exception e) {
            logger.error("get img error",e);
            return Rets.failure("获取图片异常");
        }finally{
            try {
                fis.close();
            }catch (Exception e){
                logger.error("close getImgBase64 error",e);
            }
        }

    }


    @RequestMapping(value="getImgStream",method = RequestMethod.GET)
    public void getImgStream(HttpServletResponse response,
                             @RequestParam("idFile")Long idFile){
        FileInfo fileInfo = fileService.get(idFile);
        FileInputStream fis = null;
        response.setContentType("image/"+fileInfo.getRealFileName().split("\\.")[1]);
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(fileInfo.getAblatePath());
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            logger.error("getImgStream error",e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error("close getImgStream error",e);
                }
            }
        }
    }
}
